#! /bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground

# 配置ElasticSearch
function configElasticSearch()
{

# 获取es安装文件
es_config=$1
# 获取主节点信息
master=$2
master_ip=`cat $PLAY_HOME/host_ip.txt | grep node01 | cut -d " " -f1`

# 当前节点hostname
node=`hostname`
# 当前节点IP
host_ip=$(hostname --all-ip-addresses | awk '{print $1}')

hosts_conf=$(create_conf_hosts)

cat >> $es_config <<EOF
cluster.name: es-cluster
node.name: ${node}
path.data: /var/elasticsearch/data
path.logs: /var/elasticsearch/log
network.host: ${host_ip}  
http.port: 9200 
$hosts_conf
node.master: true
node.data: true
node.ingest: true
EOF
}

function configElasticSearch_for_8()
{

# 获取es安装文件
es_config=$1
# 获取主节点信息
master=$2
master_ip=`cat $PLAY_HOME/host_ip.txt | grep node01 | cut -d " " -f1`

# 当前节点hostname
node=`hostname`
# 当前节点IP
host_ip=$(hostname --all-ip-addresses | awk '{print $1}')

hosts_conf=$(create_conf_discovery_seed_hosts)

cat >> $es_config <<EOF
cluster.name: es-cluster
node.name: ${node}
path.data: /var/elasticsearch/data
path.logs: /var/elasticsearch/log
network.host: ${host_ip}  
http.port: 9200 
$hosts_conf
cluster.initial_master_nodes: $master
xpack.security.enabled: false
xpack.security.http.ssl.enabled: false
xpack.security.transport.ssl.enabled: false
EOF
}

# Search 6.x
# 计算discovery.zen.ping.unicast.hosts的值
function create_conf_hosts()
{   
    esInfo=`egrep "elasticsearch" $PLAY_HOME/frames.txt`
    nodes=`echo $esInfo | cut -d " " -f3`

    # 将节点信息字符串拆分成数组
    IFS=',' read -ra node_array <<< "$nodes"

    # 构建配置字符串
    config="discovery.zen.ping.unicast.hosts: ["

    # 遍历节点数组，添加节点信息到配置字符串
    for node in "${node_array[@]}"
    do
        config+="\"$node\", "
    done

    # 删除最后一个逗号和空格
    config="${config%,*}"

    # 添加右括号
    config+="]"

    echo $config
}

# ES 8.x
# 计算discovery.seed_hosts的值
function create_conf_discovery_seed_hosts()
{   
    esInfo=`egrep "elasticsearch" $PLAY_HOME/frames.txt`
    nodes=`echo $esInfo | cut -d " " -f3`

    # 将节点信息字符串拆分成数组
    IFS=',' read -ra node_array <<< "$nodes"

    # 构建配置字符串
    config="discovery.seed_hosts: ["

    # 遍历节点数组，添加节点信息到配置字符串
    for node in "${node_array[@]}"
    do
        config+="\"$node:9300\", "
    done

    # 删除最后一个逗号和空格
    config="${config%,*}"

    # 添加右括号
    config+="]"

    echo $config
}

function installES()
{
 #1.在frames.txt中查看是否需要安装es
 esInfo=`egrep "elasticsearch" $PLAY_HOME/frames.txt`
 
 es=`echo $esInfo | cut -d " " -f1`
 isInstall=`echo $esInfo | cut -d " " -f2`
 installNode=`echo $esInfo | cut -d " " -f3`
 master_node=`echo $esInfo | cut -d " " -f4`
 node=`hostname`

 
 #是否安装
 if [[ $isInstall = "true" && $installNode =~ $node ]];then
    
    #2.查看$PLAY_HOME/frames目录下是否有ES安装包
    esIsExists=`find $PLAY_HOME/frames -name $es`
    if [[ ${#esIsExists} -ne 0 ]];then
        if [[ ! -d /opt/app ]];then
            mkdir /opt/app && chmod -R 775 /opt/app
        fi
   
        #删除旧的
        es_home_old=`find /opt/app -maxdepth 1 -name "*elasticsearch*"`
        for i in $es_home_old;do
            rm -rf $i
        done

        #3.解压到指定文件夹/opt/app中
        echo "开始解压elasticsearch安装包"
        
        tar -zxvf $esIsExists -C /opt/app >& /dev/null
        echo "elasticsearch安装包解压完毕"

         # 添加es用户，默认密码es
        $PLAY_HOME/systems/autoCreateUser.sh create es es
        chown -R es:es `find /opt/app -maxdepth 1 -name "*elasticsearch*"`
        # 将数据目录与日志目录赋权
        mkdir -p /var/elasticsearch/data
        mkdir -p /var/elasticsearch/log
        chown -R es:es /var/elasticsearch
        chown -R es:es /var/elasticsearch/log/

        version=$(echo "$es" | sed -n 's/elasticsearch-\([0-9.]*\)\(-linux-x86_64\)\?\.tar\.gz/\1/p')
        es_home=$(find /opt/app -maxdepth 1 -name "*elasticsearch*" | grep "$version")

        # 完成es参数配置
        # configElasticSearch $es_home/config/elasticsearch.yml $master_node

        # 检查版本号并调用对应的配置方法
        if [[ "$version" =~ ^8\. ]]; then
            # 目录授权
            chown -R es:es $es_home/config/elasticsearch.keystore
            # 配置ES
            configElasticSearch_for_8 $es_home/config/elasticsearch.yml $master_node
        else
            configElasticSearch $es_home/config/elasticsearch.yml $master_node
        fi

        #4.配置ES_HOME
        profile=/etc/profile
        sed -i "/^export ES_HOME/d" $profile
        echo "export ES_HOME=$es_home" >> $profile

        #5.配置PATH
        sed -i "/^export PATH=\$PATH:\$ES_HOME\/bin/d" $profile
        echo "export PATH=\$PATH:\$ES_HOME/bin:" >> $profile

        #6.更新/etc/profile文件
        source /etc/profile && source /etc/profile

        echo "es soft nofile 65535" | tee -a /etc/security/limits.conf
        echo "es hard nofile 65537" | tee -a /etc/security/limits.conf

        if grep -q "vm.max_map_count" /etc/sysctl.conf; then
            echo "配置项已存在，不需要追加。"
        else
            # 追加配置项到/etc/sysctl.conf文件
            echo "vm.max_map_count=262144" | tee -a /etc/sysctl.conf
            sysctl -p
        fi

    else
        echo "$PLAY_HOME/frames目录下没有ES安装包"
    fi
 else
     echo "ES不允许被安装在当前节点"
 fi

}

function uninstallES()
{

    # 获取elasticsearch安装目录
    esInfo=$(egrep "elasticsearch" $PLAY_HOME/frames.txt)
    es=$(echo $esInfo | cut -d " " -f1)
    version=$(echo "$es" | sed -n 's/elasticsearch-\([0-9.]*\)\(-linux-x86_64\)\?\.tar\.gz/\1/p')
    es_home=$(find /opt/app -maxdepth 1 -name "*elasticsearch*" | grep "$version")

    # 移除ES_HOME环境变量
    sed -i "/^export ES_HOME/d" /etc/profile
    sed -i "/^export PATH=\$PATH:\$ES_HOME\/bin/d" /etc/profile

    # 更新/etc/profile文件
    source /etc/profile

    # 删除elasticsearch/data和elasticsearch/log目录
    rm -rf /var/elasticsearch/data
    rm -rf /var/elasticsearch/log

    # 调用autoCreateUser.sh脚本删除es用户和用户组
    $PLAY_HOME/systems/autoCreateUser.sh delete es es

    echo "Elasticsearch已成功卸载"

    # 将ES从系统中移除
    rm -rf $es_home

}

# 判断输入参数并执行相应操作
if [ "$1" == "install" ]; then
    installES
elif [ "$1" == "uninstall" ]; then
    uninstallES
else
    echo "无效的参数"
fi